package org.enate.bloatterrorist;

import java.util.ArrayList;

import org.enate.bloatterrorist.AppListFragment.reloadGridView;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public final class FilterFragment extends Fragment {
    private static final String TAG = "FilterFragment";
    protected static EditText et = null;
    private static Button btn = null;
    private static ImageView iv, iv2;
    private static View v;
    private static Boolean isDefault = false;
    protected static ListView lv_searchhistory;
    private static String[] strarr_searchhistory = {};
    private static String str_searchtext = "";
    private static ArrayList<String> alsearchhistory = null;
    private static ArrayAdapter<String> aasearchhistory = null;
    private static int i, j = 0;

    protected static String[] stock_filter = {};
	private static String mfilter = "";
	private static String gvcTag = "";

    
    @Override 
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.fragment_appfilter, container, false);
    	return v;
    }

    @Override public void onActivityCreated(Bundle savedInstanceState) {
    	super.onActivityCreated(savedInstanceState);
    	v = getView();
        et = (EditText)v.findViewById(R.id.et_searchfilter);
        et.setOnKeyListener(new OnKeyListener() {
			@Override public boolean onKey(View v, int keyCode, KeyEvent event) {et.setHint("Filter by name"); return false;}
        });
        iv = (ImageView)v.findViewById(R.id.glow_appfilternormal);
        API.homeythewallsaremeltingagain(iv);
        iv.startAnimation(API.a1);
        iv2 = (ImageView)v.findViewById(R.id.glow_appfilterpress);
        btn = (Button)v.findViewById(R.id.btn_appfilter);
        btn.setOnClickListener(new OnClickListener() { 
        	public void onClick(View v) {
        		str_searchtext = et.getText().toString();
        		updateSearchHistory(str_searchtext, 1);
        		AppListFragment.reloadGridView rgv = new reloadGridView();
        		AppListFragment.mFilter = str_searchtext;
        		rgv.execute(str_searchtext);
        	}
        });
        
        btn.setOnTouchListener(API.otl_HTWAMA(iv, iv2, true));
        btn = (Button)v.findViewById(R.id.btn_clearfilter);
        btn.setOnClickListener(new OnClickListener() {public void onClick(View v) {et.setText("");}});
        lv_searchhistory = (ListView)v.findViewById(R.id.lv_searchhistory);        
		stock_filter = Main.c.getResources().getStringArray(R.array.standard_filters); 
		updateSearchHistory("", 1);
    }
    
	private static void updateSearchHistory(String searchphrase, int action){
		String str_searchhistory = "";
		alsearchhistory = new ArrayList<String>();
		mfilter = Main.prefs.getString(API.str_prefSearchHistory, "");
		strarr_searchhistory = mfilter.equals("") ? stock_filter : mfilter.split("\\|");
		if(!(1==strarr_searchhistory.length && strarr_searchhistory[0].equals(""))) {
			i = 0;
			j = strarr_searchhistory.length;
			for(i=0;i<j;i++){alsearchhistory.add(strarr_searchhistory[i]);}
	
			int spio = alsearchhistory.indexOf(searchphrase);
			if(spio>-1 && -1==action) {
				alsearchhistory.remove(spio);
			}
			j = alsearchhistory.size();
			for (i=0;i<j;i++){
				if(8==i){i=j;}
				else{str_searchhistory += alsearchhistory.get(i)+"|";}
			}
			if(spio==-1 && !searchphrase.equals("")){
				str_searchhistory = searchphrase+"|"+str_searchhistory;
				alsearchhistory.add(0, searchphrase);
			}
		}
		else {
			if(!searchphrase.equals("")) {
				str_searchhistory += "|";
				alsearchhistory.add(0, searchphrase);
			}
		}
		Main.prefs_editor.putString(API.str_prefSearchHistory, str_searchhistory).commit();
		aasearchhistory = new SearchHistoryAdapter(alsearchhistory);
		lv_searchhistory.setAdapter(aasearchhistory);
		aasearchhistory.notifyDataSetChanged();
        lv_searchhistory.setFastScrollEnabled(true);
	}
	
	private static void onLVItemClick(int childItem, int position) {
		String filtertext = lv_searchhistory.getChildAt(position).findViewById(R.id.filtertext).getTag().toString();
	
		switch(childItem) {
		case R.id.filtericon: case R.id.filtertext:
			for(i=0;i<stock_filter.length;i++){if(filtertext.equals(stock_filter[i])){isDefault=true;}}
			if(isDefault) {
				et.setText("");
				et.setHint("Showing "+filtertext);
			}
			else {
				et.setText(filtertext);
				et.setHint("Filter by name");
			}
			AppListFragment.reloadGridView rgv = new reloadGridView();
			AppListFragment.mFilter = filtertext;
    		rgv.execute(filtertext);
			break;
		case R.id.btn_delfilteritem:
			updateSearchHistory(filtertext, -1);
			break;
		}
	}
	
	protected static class SearchHistoryAdapter extends ArrayAdapter<String> {
		private ArrayList<String> arrayList;
		protected SearchHistoryAdapter(ArrayList<String> arrayList) {
			super(Main.c, R.layout.appfilter_lvitem, arrayList);
			this.arrayList = arrayList;
		}
		public View getView(final int position, View convertView, ViewGroup parent) {
			String mSearchText = arrayList.get(position);
			isDefault = false;
			ViewHolder holder;
			convertView = Main.li.inflate(R.layout.appfilter_lvitem, null);
			convertView.setTag(R.id.filtertext, mSearchText);
			holder = new ViewHolder();
	
			holder.iv_search = (ImageView) convertView.findViewById(R.id.filtericon);
			holder.iv_search.setOnClickListener(new OnClickListener() {
				@Override public void onClick(View v) {onLVItemClick(R.id.filtericon, position);}
			});
			holder.text = (TextView) convertView.findViewById(R.id.filtertext);	
			holder.text.setText(mSearchText);
			holder.text.setTag(mSearchText);
			holder.text.setOnClickListener(new OnClickListener() {
				@Override public void onClick(View v) {onLVItemClick(R.id.filtertext, position);}
			});
			holder.btn_delfilteritem = (Button) convertView.findViewById(R.id.btn_delfilteritem);
			for(i=0;i<stock_filter.length;i++){if(mSearchText.equals(stock_filter[i])){isDefault=true;}}
			if(isDefault){holder.btn_delfilteritem.setVisibility(View.GONE);}
			else{
				holder.btn_delfilteritem.setOnClickListener(new OnClickListener() {
					@Override public void onClick(View v) {onLVItemClick(R.id.btn_delfilteritem, position);}
				});
			}
			return convertView;
		}
		private class ViewHolder {
			TextView text;
			ImageView iv_search;
			Button btn_delfilteritem;
		}
	}


    @Override public void onSaveInstanceState(Bundle outState) {super.onSaveInstanceState(outState);}
}